<?php

// +----------------------------------------------------------------------
// | Author: pp <124910168@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use service\LogService;
use think\Db;

/**
 * 用户管理控制器
 * Class ClientUser
 * @package app\admin\controller
 */
class Clientuser extends BasicAdmin {

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'Client';

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->user = session('user');
        $this->uid = $this->user['id'];
        $this->categorys = db('category')->where("parentid=0")->order('sort DESC,id DESC')->column('id,catname,module,moduleid');
        $this->assign('categorys', $this->categorys);
        $this->client_user_types = config('dbx.client_user_type');
        $this->assign('client_user_types', $this->client_user_types);

        $mids = Db::name('Client')->where(['is_deleted' => 0])->column('admin_id');
        $map = [
            'status' => 1,
            'is_deleted' => '0',
            'id' => ['notin', $mids]
            ];
        $adminList = Db::name('Member')->where($map)->select();
        // halt($adminList);
        $this->assign('adminList', $adminList);
        // halt($client_user_types);
        // halt($this->categorys);
    }

    /**
     * 用户列表
     */
    public function index() {
        // 设置页面标题
        $this->title = '传承人管理';
        // 获取到所有GET参数
        $get = $this->request->get();
        // 实例Query对象
        $db = Db::name($this->table)->where('is_deleted', '0');
        // $db->where('aid', 'in', $this->aids);
        // 应用搜索条件
        foreach (['username','truename', 'phone', 'admin_id', 'aid', 'nid', 'did'] as $key) {
            if (isset($get[$key]) && $get[$key] !== '') {
                if(in_array($key, ['aid', 'nid', 'did'])){
                    $db->where($key, 'eq', $get[$key]);
                    $db->whereOr($key, 'like', "{$get[$key]},%");
                    $db->whereOr($key, 'like', "%,{$get[$key]},%");
                    $db->whereOr($key, 'like', "%,{$get[$key]}");
                }elseif($key == 'admin_id'){
                    $uids = Db::connect(config('dbx.SU'))->name('Member')->where('username', 'like', "%{$get[$key]}%")->column('id');
                    // halt($uids);
                    $db->where($key, 'in', $uids);
                }else{
                    $db->where($key, 'like', "%{$get[$key]}%");                    
                }
            }
        }
        $db->order('id desc');

        $data = parent::_list($db, true, false);
        return $this->fetch('', $data);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_data_filter(&$data)
    {
        foreach ($data as &$vo) {
            $cnames = Db::name('category')->where(array('id'=>['in', $vo['sc_id']]))->column('catname');
            // halt($cnames);
            $vo['storeclass'] = join(',', $cnames);
            $vo['typename'] = '';
            if(!empty($vo['type'])){
                // halt($this->client_user_types);
                foreach (explode(',', $vo['type']) as $k => $v) {
                    foreach ($this->client_user_types as $kk => $vv) {
                        if($v == $vv['id']){
                            $vo['typename'][$k] = $vv['title'];
                        }
                    }
                }
            $vo['typename'] = join(',', $vo['typename']);
            }
        }
    }

    /**
     * 授权管理
     * @return array|string
     */
    public function auth()
    {
        return $this->_form($this->table, 'auth');
    }

    /**
     * 授权管理表单数据默认处理
     * @param array $data
     */
    public function _auth_form_filter(&$data)
    {
        if ($this->request->isPost()) {
            // halt($data);
            $data['username'] = Db::name($this->table)->where(['id' => $data['id']])->value('username');
            Db::name($this->table)->update($data);
           // Db::name('ClientStaff')->where('create_by',$data['id'])->update(['authorize'=>$data['authorize'], 'username' => $data['username']]);
        }
    }

    /**
     * 用户添加
     */
    public function add()
    {    	
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户添加表单数据默认处理
     * @param array $data
     */
    public function _add_form_filter(&$data) {
        if ($this->request->isPost()) {
            $result=input('post.');
            if ($data['password'] !== $data['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            unset($result['repassword']);
            $result['password'] = md5($data['password']);
            unset($result['password']);
            
            //商家分类  用,分隔
            if(!empty($result['sc_id'])){
            	$result['sc_id']=trim(implode(',',$result['sc_id']),',');
            }
            if(!empty($result['type'])){
                $result['type']=trim(implode(',',$result['type']),',');
            }
            $ret=Db::name($this->table)->insertGetId($result);
            Db::name($this->table)->where(array('id'=>$ret))->update(array('create_by'=>$ret));
            unset($result['unit_name'],$result['address'],$result['repassword']);
            unset($result['sc_id']);
            $result['create_by']=$ret;
            // $res=Db::name('ClientStaff')->insert($result);
            LogService::write('系统用户', '传承人用户添加成功');
            $ret!== false ? $this->success('恭喜，保存成功哦！!', '') : $this->error('保存失败，请稍候再试！');
        }
    }

    /**
     * 用户编辑
     */
    public function edit() {    	
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户密码修改
     */
    public function pass() {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        if ($this->request->isGet()) {
            $this->assign('verify', false);
            return $this->_form($this->table, 'pass');
        }
        $data = $this->request->post();
        if ($data['password'] !== $data['repassword']) {
            $this->error('两次输入的密码不一致！');
        }
        if (DataService::save($this->table, ['id' => $data['id'], 'password' => md5($data['password'])])) {
            LogService::write('系统用户', '传承人用户密码修改成功');
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data) {
        if ($this->request->isPost()) {
            // halt($data);


            if(!empty($data['work_start'])){
                $data['work_start']=strtotime($data['work_start']);
            }

            if(!empty($data['id_images'])){
                $data['id_images']=trim(implode(';',$data['id_images']),',');
            }

            if(!empty($data['cert_images'])){
                $data['cert_images']=trim(implode(';',$data['cert_images']),',');
            }

            if (isset($data['authorize']) && is_array($data['authorize'])) {
                $data['authorize'] = join(',', $data['authorize']);
            }
            
            //商家分类  用,分隔
            if(!empty($data['sc_id'])){
            	$data['sc_id']=trim(implode(',',$data['sc_id']),',');
            }
            if(!empty($data['type'])){
                $data['type']=trim(implode(',',$data['type']),',');
            }
            if(!empty($data['readgroup'])){
                $data['readgroup']=trim(implode(',',$data['readgroup']),',');
            }
            
            // if (isset($data['id'])) {
            //     unset($data['username']);
            // } elseif (Db::name($this->table)->where('username', $data['username'])->find()) {
            //     $this->error('用户账号已经存在，请使用其它账号！');
            // }
        } else {

            if(!empty($data['work_start'])){
                $data['work_start']=date('Y-m-d',$data['work_start']);
            }
            if(!empty($data['id_images'])){
                $data['id_images']=explode(';',$data['id_images']);
            }
            if(!empty($data['cert_images'])){
                $data['cert_images']=explode(';',$data['cert_images']);
            }
            if(!empty($data['readgroup'])){
                $data['readgroup']=explode(',',$data['readgroup']);
            }else{
                $data['readgroup'] = [1];
            }
            if(!empty($data['aid'])){
                $data['aid']=explode(',',$data['aid']);
            }
            if(!empty($data['nid'])){
                $data['nid']=explode(',',$data['nid']);
            }
            if(!empty($data['did'])){
                $data['did']=explode(',',$data['did']);
            }

            // //获取地区
            // $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
            // $this->assign('areaList', $areaList);
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->assign('authorizes', Db::name('ClientAuth')->where('create_by',0)->select());

            $newareas = ToolsService::arr2subs($this->newareas, $data['aid']);
            $this->assign('newareas', $newareas);
            $newnations = ToolsService::arr2subss($this->newnations, $data['nid']);
            $this->assign('newnations', $newnations);
            $newdiseases = ToolsService::arr2subss($this->newdiseases, $data['did']);
            $this->assign('newdiseases', $newdiseases);
        }
    }

    /**
     * 删除用户
     */
    public function del() {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '传承人用户删除成功');
            $this->success("用户删除成功！", '');
        }
        $this->error("用户删除失败，请稍候再试！");
    }

    /**
     * 用户禁用
     */
    public function forbid() {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '传承人用户禁用成功');
            $this->success("用户禁用成功！", '');
        }
        $this->error("用户禁用失败，请稍候再试！");
    }

    /**
     * 用户启用
     */
    public function resume() {
        if (DataService::update($this->table)) {
            LogService::write('系统用户', '传承人用户启用成功');
            $this->success("用户启用成功！", '');
        }
        $this->error("用户启用失败，请稍候再试！");
    }

    //批量审核
    public function statusAll(){
        $map['id'] =array('in',input('post.ids/a'));
        Db::name($this->table)->where($map)->update(['status'=>1]);
        LogService::write('传承人', '传承人批量审核成功');
        $result['code'] = 1;
        $result['msg'] = '批量审核成功！';
        $result['url'] = url('index',array('catid'=>input('post.catid')));
        return $result;
    }

    //取消批量审核
    public function statusCancelAll(){
        $map['id'] =array('in',input('post.ids/a'));
        Db::name($this->table)->where($map)->update(['status'=>0]);
        LogService::write('传承人', '传承人批量取消审核成功');
        $result['code'] = 1;
        $result['msg'] = '批量取消审核成功！';
        $result['url'] = url('index',array('catid'=>input('post.catid')));
        return $result;
    }

}
